﻿/**
 * 通用FORM方法封装处理
 *
 */
import {clearZero, dateFormatYYYYMMDDHHmmss, deepClone, uniqBy} from './index';
import {findComponentsDownward, findComponentsUpward} from './findVueDom';
import {lodashFillData,lodashUniqBy} from "@/utils/lodashUtil";

//通用 data数据
export const formData = {
  // 遮罩层
  loading: true,
  // 导出遮罩层
  exportLoading: false,

  fullscreenLoading: false,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 表格数据
  dataList: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 状态数据字典
  statusOptions: [],
  logs: {
    loading: true,
    open: false,
    // 查询日志参数
    queryParams: {
      pageNum: 1,
      pageSize: 30,
      infoId: undefined,
      costGroup: '',
    },
    dataList: [],
    // 总条数
    total: 0,

  },

  // 通用的表格字段 显示隐藏 控制
  columnsHidden: {},

  //加载按钮loading
  loadingStatus: {
    modify: false, //update or add
    search: false,
  },
  //是否第一次进入界面
  isFirstEnter: true,
  //是否出发 更多查询
  isTriggerMoreSearch: false,
  formOneClientWidth: Math.floor($('.main-container').width() / 206),
};

//通用分页查询条件
export const PageData = {
  pageNum: 1,
  pageSize: 10,
};

export function uniqWithKey(data, key, uniqId = 'id') {
  //数组 去重

  if (data && Array.isArray(data)) {
    data = data.map(item => {

      if (item && item.hasOwnProperty(key)) {
        item[key] = uniqBy(item[key], uniqId);
        return item;
      }
      return item;
    });
    return data;
  }

  //对象 去重
  if (data && data.toString() === '[object Object]') {
    if (data && data.hasOwnProperty(key)) {
      data[key] = uniqBy(data[key], uniqId);
      return data;
    }
  }

  //其他情况不处理
  return data;
}

//通用操作方法
export const formMethod = {
  /** 查询列表 */
  getInfoList() {
    var self = this;
    this.loading = true;
    this.queryParams.addTimeStar = dateFormatYYYYMMDDHHmmss(this.queryParams.starEndArray && this.queryParams.starEndArray[0]);
    this.queryParams.addTimeEnd = this.$endOfTimeByDay(this.queryParams.starEndArray && this.queryParams.starEndArray[1]);
    return this.api.getList(this.queryParams).then((response) => {

      //特殊数据id的唯一性
      response.data = uniqWithKey(response && response.data, 'funs', 'id');

      var datalist = response && response.data && response.data.map((item, index) => {
        return item;
      });

      self.dataList = datalist;

      self.total = response && response.count;
      self.loading = false;
      //self.ajaxGetPayApplyGroupState();

    });
  },


  /**
   * @description: 搜索条件不一样  可以出发不一样的查询
   * @params
   * @return
   */
  setQueryKeyForStr(str, queryParams) {
    var str1 = str && str.toLocaleLowerCase();
    queryParams.planNo = '';
    queryParams.proCode = '';
    queryParams.roNo = '';
    if (/*planNo*/str1 && str1.indexOf('test') >= 0 ||
      str1 && str1.indexOf('po') >= 0
    ) {
      queryParams.planNo = str;
    } else if (str1 && str1.indexOf('pa') >= 0) {
      queryParams.roNo = str;
    } else {
      /*默认 产品*/
      queryParams.proCode = str;
    }
  },

  /** 查询变更日志列表 */
  getLogsList(row) {
    // console.log(row);
    if (row && row.id) {
      this.logs.queryParams.infoId = row.id;
    }
    if (!this.logs.queryParams.infoId) {
      this.msgError('请先选择要查询的数据');
      return;
    }
    this.logs.open = true;
    this.logs.loading = true;
    this.api.getLogs(this.logs.queryParams).then((response) => {
      this.logs.dataList = response.data;
      this.logs.total = response.count;
      this.logs.loading = false;
    });
  },
  // 状态字典翻译
  statusFormat(row, column) {
    return this.selectDictLabel(this.statusOptions, row.state);
  },
  // 取消按钮
  cancel() {
    this.open = false;
    this.reset();
  },
  // 表单重置
  reset() {
    this.form = {
      id: undefined,
      name: undefined,
      version: undefined,
      gateway: undefined,
      state: '1',
      appType: '1',
      description: undefined,
    };
    this.resetForm('form');

  },
  /** 搜索按钮操作 */


  handleQuery() {
    this.beforeQuery && this.beforeQuery();
    this.loadingStatus.search = true;
    this.queryParams.pageNum = 1;
    this.getInfoList().then(res => {
      this.loadingStatus.search = false;
    });
  },
  /** 重置按钮操作 */
  resetQuery(whitlist=[]) {
    var self=this
    this.resetForm('queryForm');
    if(this.queryParams){
      lodashFillData(this.queryParams,{
        pageSize:10
      },whitlist)
    }


    this.handleQuery();
  },
  /*显示更多条件*/
  triggerShowMoreSearch(fomref = 'queryForm') {
    /*  var formdom = this.$refs[fomref].$el;
      var formdomchildren = $(formdom).find('.el-form-item');
      //一行 有多少 formitem
      if (!this.isTriggerMoreSearch) {
        for (let i = 0; i < formdomchildren.length; i++) {
          var displaynone = $(formdomchildren[i]).css('display');
          if (displaynone === 'none') {
            $(formdomchildren[i]).css({ display: 'inline-block' });
          }
        }
      } else {
        this.displayFormTo1row(fomref);
      }*/
    this.isTriggerMoreSearch = !this.isTriggerMoreSearch;
  },
  displayFormTo1row(fomref = 'queryForm') {
    var formdom = this.$refs[fomref].$el;
    var formdomchildren = $(formdom).find('.el-form-item');
    var oneChild = formdomchildren && formdomchildren[0];
    //一行 有多少 formitem
    console.log('oneChild && oneChild.clientWidth', oneChild && oneChild.clientWidth + 40);
    var onerowLength = Math.floor($('.main-container').width() / (oneChild && oneChild.clientWidth + 40));
    console.log('一行 有多少 formitem onerowLength', onerowLength);
    for (let i = 0; i < formdomchildren.length - 1; i++) {
      if (i >= onerowLength - 1) {
        //隐藏
        $(formdomchildren[i]).css({display: 'none'});
      }
    }
  },

  /** 多选框选中数据 */
  handleSelectionChange(selection) {
    this.ids = selection.map((item) => item.id);
    this.single = selection.length != 1;
    this.multiple = !selection.length;
  },
  /** 新增按钮操作 */
  handleAdd() {
    this.reset();
    this.open = true;
    this.title = '添加信息';
  },

  /** 修改按钮操作 */
  handleUpdate(row) {
    this.reset();
    if ((!row || !row.id) && this.ids.length > 1) {
      this.msgError('每次只能编辑一条信息');
      return;
    }

    const postId = row.id || this.ids[0];
    this.api.getItem(postId).then((response) => {
      this.form = response.data;
      this.form.state += ''; //解决数字类型 单选框无法选中的问题
      this.open = true;
      this.title = '修改信息';
    });
  },
  /** 提交按钮 */
  submitForm: function () {
    this.$data.loadingStatus.modify = true;
    this.$refs['form'].validate((valid) => {
      if (valid) {
        if (this.form.id != undefined) {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          });
          this.fullscreenLoading = true;
          this.api.update(this.form).then((response) => {
            loading.close();

            setTimeout(() => {
              this.$data.loadingStatus.modify = false;
            }, 500);

            this.msgSuccess('修改成功');
            this.afterSuccess();

            this.open = false;
            this.getInfoList();

          }).catch((err) => {
            loading.close();
            setTimeout(() => {
              this.$data.loadingStatus.modify = false;
            }, 500);
          });
        } else {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          });
          this.fullscreenLoading = true;
          this.api.add(this.form).then((response) => {
            loading.close();
            this.msgSuccess('新增成功');
            setTimeout(() => {
              this.$data.loadingStatus.modify = false;
            }, 500);

            this.open = false;
            this.getInfoList();
            this.afterSuccess && this.afterSuccess();

          }).catch((err) => {
            this.fullscreenLoading = false;
            loading.close();
            setTimeout(() => {
              this.$data.loadingStatus.modify = false;
            }, 500);
          });
        }
      } else {
        setTimeout(() => {
          this.$data.loadingStatus.modify = false;
        }, 500);
      }
    });
  },

  /** 删除按钮操作 */
  handleDelete(row) {
    if ((!row || !row.id) && this.ids.length > 1) {
      this.msgError('禁止批量删除');
      return Promise.resolve(false);
    }
    let that = this;
    const postIds = row.id || this.ids[0];
    return this.$confirm(
      '是否确认删除编号为"' + postIds + '"的数据项?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(function () {
        return that.api.del(postIds);
      })
      .then(() => {
        that.getInfoList();
        that.msgSuccess('删除成功');
        that.afterDeleteSuccess &&
        that.afterDeleteSuccess();
        return Promise.resolve(true);
      })
      .catch(() => {
        return Promise.resolve(false);
        // this.msgError("删除失败");
      });
  },

  /** 显示日志弹出框 */
  openLog(row,queryParams) {
    if (!(this.api && this.api.getLogs)) {
      this.msgError('没有获取日志方法');
      return false;
    }
    this.$openLog({
      id: row.id,
      api: this.api.getLogs,
      queryParams:queryParams
    });
  },

  /** 导入数据弹出框 */
  openImportDialog(dataType, exParams) {
    if (!dataType) {
      this.msgError('缺少需要导入的类型');
      return false;
    }
    this.$openImportDialog({
      dataType,
      exParams,
      success: () => {
        this.getInfoList();
      },
    });
  },
  /** 初始化 查询表单的显示和关闭*/
  initSearchFormDisplay() {
    this._hiddenFormItems();
  },
  /**region:显示和隐藏查询表达*/
  triggerSeeMore(_val) {
    if (_val) {
      this._showFormItems();
    } else {
      this._hiddenFormItems();
    }
  },
  _showFormItems() {
    var $items = findComponentsDownward(this.$refs['queryForm'], 'ElFormItem');
    for (let i = 0; i < $items.length; i++) {
      if (i > 4) {
        var item = $items[i];
        var dom = item.$el;
        $(dom).css({display: 'inline-flex'});
      }
    }

  },
  _hiddenFormItems() {
    var $items = findComponentsDownward(this.$refs['queryForm'], 'ElFormItem');
    for (let i = 0; i < $items.length; i++) {
      if (i > 4) {
        var item = $items[i];
        var dom = item.$el;
        $(dom).css({display: 'none'});
      }
    }
  },
  /**endregion:显示和隐藏查询表达*/


  /**region:modify.vue界面的公有方法*/
  //提交方法
  submitFormInModify() {
    this.loadingStatus.modify = true;

    this.$refs['form'] &&
    this.$refs['form'].clearValidate &&
    this.$refs['form'].clearValidate();
    this.$refs['form'].validate(async (isyes) => {
      if (isyes) {
        var _params = deepClone(this.form);
        _params = this.dataForSubmit(_params);
        var ajaxFun = this.form.id ? this.api.update : this.api.add;
        console.log('[get]', ajaxFun);
        // console.log('参数', JSON.stringify(_params));
        ajaxFun(_params).then(res => res.data).then(result => {
          console.log('结果', result);
          this.dialogVisible = false;
          setTimeout(() => {
            this.loadingStatus.modify = false;
          }, 500);
          this.resetForm('form');
          this.$emit('refresh');
          this.afterSumbit && this.afterSumbit(result);
        }).catch(e => {
          console.error(e);
          setTimeout(() => {
            this.loadingStatus.modify = false;
          }, 500);
        });

      } else {
        setTimeout(() => {
          this.loadingStatus.modify = false;
        }, 500);
      }
    });
  },
  //提交之前调整数据,此方法会被大量重写
  dataForSubmit(data) {
    return data;
  },

  //初始化弹出框的时候需要处理的数据,此方法会被大量重写
  dataForShow(data) {
    clearZero(data);

    return data;
  },
  //处理关闭弹出框之后
  handleClose() {
    this.$data.dialogVisible = false;
    this.loadingStatus.modify = false;
    this.$refs['form'] && this.$refs['form'].resetFields();
  },
  //弹出框 内部公共处理方法，让弹出框使用者值专注业务代码的处理
  __init(_data) {
    this.title = _data && _data.id ? '修改' : '添加';
    this.dialogVisible = true;
  },
  /**endregion:modify.vue界面的公有方法*/

};



